C言語 文字列操作
C言語 文字列操作
文字列join、文字列→数値
code:string.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
* 文字列のjoin
*/
char * join_strings(const char **strings, size_t count) {
size_t totalLength = 1;
for (size_t i = 0; i < count; i++) {
totalLength += strlen(stringsi) + (i < (count - 1) ? 1 : 0);
}
// 結果となる文字列用のメモリを確保
char *result = malloc(totalLength);
if (result == NULL) {
// メモリ確保失敗
return NULL;
}
result0 = '\0';
// 文字列を結合
for (size_t i = 0; i < count; i++) {
strcat(result, stringsi);
if (i < (count - 1)) {
strcat(result, ",");
}
}
return result;
}
int main() {
char buf256 = { '\0' };
printf("文字列の入力: ");
// &bufではない
scanf("%s", buf);
printf("文字列の出力: %s\n", buf);
// 文字列定義(静的)
// サイズをピッタリで定義する場合 文字列の長さ + 1で配列を定義する
// 変更しない文字列にはconstをつける
const char hello6 = "Hello";
const char world7 = "world!";
printf("%s, %s\n", hello, world);
// 複数個の文字列(静的)
const char abcde[]3 = { "ab", "cd", "ef" };
printf("複数の文字列の出力: \n");
for (int i = 0; i < 3; i++) {
printf("%s\n", abcdei);
}
// 文字列(動的配列)
// 2次元の配列(動的)
int a[] = {1, 2, 3};
// 配列の長さの算出
size_t a_size = sizeof(a) / sizeof(a0);
char *strArraya_size;
for (size_t i = 0; i < a_size; i++) {
char *str = malloc(20);
sprintf(str, "%d", ai);
strArrayi = str;
}
char *joinedString = join_strings((const char **)strArray, a_size);
if (joinedString != NULL) {
printf("%s\n", joinedString);
free(joinedString);
}
// 文字列→数値
char str1000;
char *e;
scanf("%s", str);
const int s1 = (int)strtol(str, &e, 10);
printf("%d", s1);
}
$ curl -O https://scrapbox.io/api/code/pogi-log/C%E8%A8%80%E8%AA%9E_%E6%96%87%E5%AD%97%E5%88%97%E6%93%8D%E4%BD%9C/string.c; gcc -Wall -Wextra string.c && ./a.out
code:memo
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1813 0 1813 0 0 2142 0 --:--:-- --:--:-- --:--:-- 2143
文字列の入力: asdf
文字列の出力: asdf
Hello, world!
複数の文字列の出力:
ab
cd
ef
1],2,[3
C言語 配列
セキュアコーディング
SEI CERT C Coding Standard
STR06-C. strtok() が分割対象文字列を変更しないと想定しない
確認用
Q. C言語 文字列操作
Q. 文字列のjoin
Q. 文字列→数値
参考
逆引き | Programming Place Plus C言語編 逆引き
文字列を空にする | Programming Place Plus C言語編 逆引き
フォーマット指定子一覧
Ubuntu Manpage: scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf - 書式付き入力変換
strcat
メモ
各種テスト - gcc - 警告関連のオプション - フォーマット文字列関連のオプション - -Wformat-truncation
調査用
/pogi-log/Google.icon C言語 文字列操作(日)
/pogi-log/Google.icon C string operations(英)
#プログラミング操作、記述 #プログラミング操作、記述@文字列操作